import os
import time
import cgi
from operator import attrgetter
from google.appengine.ext import db

# Datastore classes
class Event(db.Model):
	sorter = db.IntegerProperty()
	DateID = db.StringProperty()	
	Title = db.StringProperty()
	Date = db.StringProperty()
	Location = db.StringProperty()
	Description = db.TextProperty()
	
class Story(db.Model):
	sorter = db.IntegerProperty()
	Date = db.StringProperty()	
	Title = db.StringProperty()
	Contents = db.TextProperty()
	
class HomeComponent(db.Model):
	sorter = db.IntegerProperty()
	Type = db.StringProperty()
	Contents = db.TextProperty()
	

# FUNCTIONS
# Get variable from HTTP		
def getVar(self, var):
	return cgi.escape(self.request.get(var)) if cgi.escape(self.request.get(var)) != '' else ''
	
# Get timestamp of when file was last updated
def getLastUpdated(fname):
	return time.strftime("%H:%M:%S %d/%m/%Y", time.localtime(os.path.getmtime(fname)))
	
# Get latest news story
def getLatestNewsStory():	
	query = Story.all()
	news = query.fetch(10)
	
	for story in news:
		day = int(story.Date[:2])
		month = int(story.Date[3:5])
		year = int(story.Date[6:8])
	
		# Set news sorter
		story.sorter = year*10000 + month*100 + day
		
	# Sort news stories in order of date
	news = sorted(news, key=attrgetter('sorter'), reverse=True)
	
	if len(news) > 0:
		return news[0]
	else:
		return ''